/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package socof_webcrawler;

import java.util.concurrent.Semaphore;

public class ResizeableSemaphore extends Semaphore {

    private int permit;

    public ResizeableSemaphore(int permit) {
        super(permit);
        this.permit = permit;
    }

    public synchronized void resizeIfRequired(int newPermit) {
        int delta = newPermit - permit;
        if (delta == 0) {
            return;
        }
        if (delta > permit) {
            this.release(delta); // this will increase capacity
        }
        if (delta < 0) {
            this.reducePermits(Math.abs(delta));
        }
        this.permit = newPermit;
    }

    public synchronized void addPermit() {
        this.release(1); // this will increase capacity
        this.permit++;
    }

    public synchronized void removePermit() {
        this.reducePermits(1); // this will reduce capacity
        this.permit--;
    }

    public synchronized int getTotalPermits() {
        return this.permit;
    }

    public synchronized void removeAllPermits() {
        this.reducePermits(this.permit);
        this.permit = 0;
    }
}
